package com.milo.concurrent;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author: Milogenius
 * @create: 2019-04-29 15:32
 * @description: 演示Semaphore的用法
 *
 * <p>
 * Semaphore（信号量）是用来控制同时访问特定资源的线程数量，它通过协调各个线程，以保证合理的使用公共资源。
 * </p>
 **/
@Slf4j
public class SemaphoreTest {

    /**排队总人数（请求总数）*/
    public static int clientTotal = 10;

    /**可同时受理业务的窗口数量（同时并发执行的线程数）*/
    public static int threadTotal = 2;

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            final int count = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire(1);
                    resolve(count);
                    semaphore.release(1);
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    private static void resolve(int i) throws InterruptedException {
        log.info("服务号{}，受理业务中。。。", i);
        Thread.sleep(2000);
    }

}
